package com.wurao.realm;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.wurao.entity.Blogger;
import com.wurao.entity.Permission;
import com.wurao.entity.Role;
import com.wurao.service.BloggerService;

/**
 * 自定义Realm
 * @author Administrator
 *
 */
public class MyRealm extends AuthorizingRealm{
	@Resource
	private BloggerService bloggerService;
	/**
     * 添加角色 
     * @param info
     */  
    private void addRole(String userName, SimpleAuthorizationInfo info) {  
        List<Role> roles = bloggerService.findByBlogger(userName);  
        if(roles!=null&&roles.size()>0){  
            for (Role role : roles) {  
                info.addRole(role.getRoleName());  
            }  
        }  
    }
    /**
     * 验证当前登录的用户
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName=(String) token.getPrincipal();
        Blogger blogger=bloggerService.getByUserName(userName);
        if(blogger!=null){
            SecurityUtils.getSubject().getSession().setAttribute("currentUser", blogger); // 把当前用户信息存到session中
            AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(blogger.getUserName(), blogger.getPassword(), "xx");
           // System.out.println(1);
            return authcInfo;
        }else{
            return null;
        }
    }
    /**
     * 添加权限 
     * @param info
     * @return 
     */  
    private SimpleAuthorizationInfo addPermission(String userName,SimpleAuthorizationInfo info) {  
        List<Permission> permissions = bloggerService.findPermissionByName(userName);  
        for (Permission permission : permissions) {
            info.addStringPermission(permission.getPermissionName());//添加权限    
        }
       // System.out.println(2);
        return info;
    }
    /**
     * 获取授权信息 
     */  
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	String blogger =(String)principals.getPrimaryPrincipal();
    	//根据用户名来添加相应的权限和角色  
        if(blogger!=null){  
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
            addPermission(blogger,info);  
            addRole(blogger, info);  
            //System.out.println("进来了--------------------------------------------3");
            return info;
        }  
        return null;
    }  


}
